package org.algorithm.biubiu.wheel_1.链表;

import org.algorithm.biubiu.wheel_1.common.ListNode;
import org.junit.Test;

/**
 * @author jiazhaoxin
 * @Date 2022/2/21
 * @Desc {https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/submissions/}
 */
public class 删除链表的倒数第n个结点 {


    @Test
    public void test() {
        ListNode listNode = removeNthFromEnd(ListNode.build(1, 2), 2);
        System.out.println("listNode = " + listNode);
    }

    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head == null) {
            return head;
        }
        ListNode node = new ListNode(-1);
        node.next = head;
        head = node;
        ListNode fast = head;
        ListNode slow = head;

        ListNode slowPrev = head;
        ListNode slowPost = head;
        for (int i = 1; i < n; i++) {
            fast = fast.next;
        }
        while (fast != null) {
            fast = fast.next;
            if (fast != null) {
                slowPrev = slow;
                slow = slow.next;
                slowPost = slow.next;
            }
        }
        if (slowPrev != slowPost) {
            slowPrev.next = slowPost;
            return head.next;
        } else {
            return null;
        }
    }
}
